<?php

class Patient extends MY_Controller {

	function __construct()
	{
		parent::__construct();
		$this->page=$this->module_codes['Patient'];
		$this->load->model('patient_model' , 'PM');
	}

	function index()
	{
		
        $this->check_page_permission('access');
		$result = $this->PM->get_patient_data();

		//if $result['count'] = 0 then there is no data
		//else generate array for all patient(s)
		if($result['count'] == 0){
			$this->data['count'] = 0;
		}
		else{
			$this->data['count'] = $result['count'];
			$this->data['result'] = $result['info'];
		}

		$this->load->view('head');
		$this->load->view('patient/main', $this->data);
		$this->load->view('footer');
		
		
	}
    
	function test_pdf()
	{
		$this->load->helper('pdf_style');
		$pdf_info = general_pdf();
		
		$this->load->plugin('to_pdf');
		create_pdf($pdf_info, 'history_report','reports');
	}
	
	function history_report($patient_id,$preview_date){
		
          $this->check_page_permission('access');
		  $this->load->model('patient_history_model', 'PHM');
		  $result=  $this->PHM->get_history($patient_id,$preview_date);
		  $this->load->model('setting_model', 'SM');
		  
		  $reportSetting=  $this->SM->getSetting('PDF');
		  //Get all the examination list and there description
            $exam=$this->get_exam_desc();
            //Get all the list price and there description
            $check =$this-> get_checkup_desc();
		  
		  $result=$this->_prepare_history($result);
		  
		//  print_r($result);
		$html="<html><head><style>
			body {font-family: Arial}
			
			
			
		</style>
		
		
		<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
		
		</head>
		
		<body>";
		      if(!empty($result))
    foreach ($result['result'] as $preview_date=>$preview_array)
    {
        //echo $count.'   '.$i;
		
        $html.= "<h2>". lang('form_label_date')." ". $preview_date."</h2>";
        
              
        
        $html.= "<div style='border:1px solid; font-size:12px;'>";
        
        if(!empty($preview_array['examination'])){
           $html.= "<div> <u>Examination</u><br>";
           $html.= "<ul>";
        
        	foreach ($preview_array['examination'] as $examination_id){
                
                 if(!empty($exam[$examination_id]))
                  $html.= "<li>".$exam[$examination_id]."</li>";
        	}
            
        	
        	$html.= "</ul>";
            $html.= "</div>";
        	
        
        }
        
        if(!empty($preview_array['checkup'])){
           $html.= "<div> <u>Checkup</u><br>";
           $html.= "<ul>";
        
        	foreach ($preview_array['checkup'] as $checkup_id){

        		
     if(!empty($check[$checkup_id]))
                  $html.= "<li>".$check[$checkup_id]."</li>";
        	        	}
            
        	
        	$html.= "</ul>";
            $html.= "</div>";
        	
        
        }
        if(!empty($preview_array['note']))
         $html.= "<div>".$preview_array['note']."</div>";

         
         
         
        	$html.= "</div>";
         
       
        	
    }    
    $html.= "</body></html>";
		  
     $this->load->plugin('to_pdf');
  //die($html);
     create_pdf($html, 'history_report',$reportSetting);
	}
	
	

	function new_patient($id='')
	{
		
        $this->check_page_permission('add');
		$patient_info	 = $id ? $this->PM->get_patient_data($id) : array();
		$submit_data = $this->input->post('patient_form');
		$submit_data = !is_array($submit_data) ? array() : $submit_data;

		$this->load->view('head');
		$this->load->view('patient/patient_form' , array_merge($patient_info,$submit_data));
		$this->load->view('footer');
	}


	function new_patient_min($id='')
	{
		
        $this->check_page_permission('add');
		$patient_info	 = $id ? $this->PM->get_patient_data($id) : array();
		$submit_data = $this->input->post('patient_form');
		$submit_data = !is_array($submit_data) ? array() : $submit_data;
		$data["form_action"] = "new_patient_min2";
		$this->load->view('patient/patient_form' ,array_merge($data , array_merge($patient_info,$submit_data)) );
	}

	function new_patient_min2()
	{
		$data = $this->input->post('patient_form');

		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');

		if ($this->form_validation->run('patient') == FALSE)
		{
			return $this->new_patient_min();
		}
		else
		{
			
              $this->check_page_permission('add');
			if($this->PM->insert_new_patient($data))
			{
				echo "<script> window.history.back() </script>";
			}
		}
	}

	function do_upload1($code){

		if(isset($code))
			$data['patient_code'] = $code;
		$this->load->view('patient/upload_form', $data);
		}
	
	function do_upload_test($code)
	{
		$this->load->library('uploader');
	}
	
	
	function do_upload()
	{
		
        $this->check_page_permission('add');
		$code=$this->input->post('code', TRUE);
		$this->load->model('setting_model', 'SM');
		$attachSetting= $this->SM->getSetting('Attachment');
		
		$upload_path='./AttachedData/'.$code.'/';

		if(!is_dir($upload_path))mkdir($upload_path) ;
		$config['upload_path'] = $upload_path;
		$config['allowed_types'] =$attachSetting['types'];
		$config['max_size']	= $attachSetting['max_size']*1024;

		$this->load->library('upload', $config);

		if ( $this->upload->do_upload())
		{
			$data = array('upload_data' => $this->upload->data());
			return "success";
			//$this->load->view('patient/upload_success', $data);
		}else
		print_r($this->upload->display_errors());
	}
	function patient_details($id=NULL)
	{
		
              $this->check_page_permission('access');

		//Get some info about the patient
                $data['patient_info'] = $this->PM->get_patient_data($id);
                $data['patient_id'] = $id;

		//$data = array();
		if($this->input->post('submit'))
		{
                    $form_data = $this->input->post('patient_form');
                    //print_r($form_data);
                    //die;
			if(isset($form_data['patient_id']))
                        {
                            $data['patient_info'] = $this->PM->get_patient_data($id);
                            if($this->PM->insert_patient_details($form_data))
                                {
                                    $data = array_merge($form_data,$data);
                                }
                        }

		}
		else
		{
                    $details    = $id ? $this->PM->get_patient_details($id) : array();
                    if(isset($details['count']) && $details['count'])
                    $data = array_merge($details[0],$data);
		}

		$data['attachements']=$this->get_attachments($data['patient_info']['code']);
	
		$this->load->view('head');
		$this->load->view('patient/details_form' , $data);
		$this->load->view('footer');
	}
	function get_attachments($patient_code,$isajax=0){
		
         $this->check_page_permission('access');
		$dir='./AttachedData/'.$patient_code;
		$attachements=array();
	if(is_dir($dir))
    	if ($handle = opendir($dir)) {

	    while (false !== ($file = readdir($handle))) {
	    	if($file=='.') continue;
	    	if($file=='..') continue;
	        $attachements[]=$file;
	    }
       
       closedir($handle);
     }
     if($isajax) echo json_encode($attachements);
     return $attachements;
		
	}
	function _prepare_history($result){
		 $history=array();
		// print_r($result);
			   if(!empty($result))
	    foreach ($result as $i=>$dt)
	    {
	    	//print_r($dt);
	    	
	         if(!empty($dt['examination_id']))
	          $history['result'][$dt['preview_date']]['examination'][$dt['examination_id']]=$dt['examination_id'];
	         	
	         if(!empty($dt['checkup_id']))
	          $history['result'][$dt['preview_date']]['checkup'][$dt['checkup_id']]=$dt['checkup_id'];
	          
	          $history['result'][$dt['preview_date']]['note']=$dt['note'];
	         	
	    }
 
	    //print_r($history);
	    return $history;
		
	}

	function patient_history($id=NULL)
	{

              $this->check_page_permission('access');
		    $this->load->model('patient_history_model', 'PHM');
            $result=  $this->PHM->get_history($id);

            //Get all the examination list and there description
            $data['exam']=$this->get_exam_desc();
            //Get all the list price and there description
            $data['check'] =$this-> get_checkup_desc();
            //Get some info about the patient
            $data['patient_info'] = $this->PM->get_patient_data($id);
            $history=$this->_prepare_history($result);      
			$this->load->view('head');
			$this->load->view('patient/patient_history', array_merge($data, $history));
			$this->load->view('footer');
	}
    function get_exam_desc(){
    	
              $this->check_page_permission('access');
   	        $this->load->model('preview_model');

            //Get all the examination list and there description
            $data=array();
            $exam_array = $this->preview_model->get_list_preview();
            foreach($exam_array['info'] as $i=>$exam_info){
            $data[$exam_info['id']]=$exam_info['description'];	
            }
          return $data;
    	
    }
    function get_checkup_desc(){
    	
              $this->check_page_permission('access');
            $this->load->model('list_price_model');

            //Get all the list price and there description
            $data = array();
            $check_array=$this->list_price_model->get_list_price();
	        foreach($check_array['info'] as $i=>$check_info){
            $data[$check_info['id']]=$check_info['test_name'];	
            }
          return $data;
    }
	function new_patient2($id=NULL)
	{
		
		$data = $this->input->post('patient_form');

		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		$id =  $data['id'];
		if ($this->form_validation->run('patient') == FALSE)
		{
			return $this->new_patient();
		}
		else
		{

			//Edit:
			if(isset($id) && $id!=''){
				
              $this->check_page_permission('edit');
				if($this->PM->update_patient_by_id($data, $id))
				redirect('patient/' , 'refresh');
				else echo "<script>
					alert('".lang('code_exists')."')
					window.history.back() </script>";
			}
			else{
				
              $this->check_page_permission('add');
				if($this->PM->insert_new_patient($data))
					redirect('patient/' , 'refresh');
				else echo "<script>
					alert('".lang('code_exists')."')
					window.history.back() </script>";
			}
		}
	}

	function delete_patient($id)
	{
		
         $this->check_page_permission('delete');// not used
		if(isset($id) && $id!=''){
			if($this->PM->delete_patient_by_id($id))
			redirect('patient/' , 'refresh');
		}
	}
	
	 function get_last_visit($patient_id){
	 	
              $this->check_page_permission('access');
		  $this->load->model('patient_history_model', 'PHM');
		  $result=  $this->PHM->get_history($patient_id);
       		 $history=$lastvisit=array();
       		 $count=0;
		// print_r($result);
			   if(!empty($result))
	    foreach ($result as $i=>$dt)
	    {
	    	//print_r($dt);
	    	 if($count && empty($history[$dt['preview_date']])) break;  
	         if(!empty($dt['examination_id']))
	          $history[$dt['preview_date']]['examination'][$dt['examination_id']]=$dt['examination_id'];
	         	
	         if(!empty($dt['checkup_id']))
	          $history[$dt['preview_date']]['checkup'][$dt['checkup_id']]=$dt['checkup_id'];
	          
	          $history[$dt['preview_date']]['note']=$dt['note'];
	         	$count++;
	    }
	       //Get all the examination list and there description
            $exam_names=$this->get_exam_desc();
            //Get all the list price and there description
            $checkup_names =$this-> get_checkup_desc();
	    
         if(count($history))
		    foreach($history as $preview_date=>$preview_array){
	          	$lastvisit['preview_date']=$preview_date;
	          	$lastvisit['note']=$preview_array['note'];
	          	if(!empty($preview_array['examination']))
	          	 foreach ($preview_array['examination'] as $id)
	          	  $lastvisit['examination'][$id]=(!empty($exam_names[$id]))?$exam_names[$id]:'';
	          	 if(!empty($preview_array['checkup'])) 
	          	 foreach ($preview_array['checkup'] as $id)
	          	  $lastvisit['checkup'][$id]=(!empty($checkup_names[$id]))?$checkup_names[$id]:'';
	          	  
	          }
	          
           
        	echo json_encode($lastvisit);
        }
	

}

/* End of file patient.php */
/* Location: ./system/application/controllers/patient.php */
